import {onUnmounted, onMounted} from 'vue'
import mitt from 'mitt'

const emitter: mitt.Emitter = mitt()

// 自定义触发器
const customEmit = (eventName) => emitter.emit(eventName)

// 自定义接收器
const customOn = (eventName, callback) => {
    const onEvent = () => callback()
    emitter.on(eventName, onEvent)
    onUnmounted(() => emitter.off(eventName, onEvent))
}

// 通知刷新表格数据
const toRefreshTable = () => {
    emitter.emit('refreshTable')
}

// 刷新表格数据
const refreshTable = (callback) => customOn('refreshTable', callback)

// 通知刷新树结构数据
const toRefreshTree = () => emitter.emit('refreshTree')

// 刷新树数据
const refreshTree = (callback) => customOn('refreshTree', callback)

export const useEventbus = () => {
    // onUnmounted(() => {
    //     emitter.all.clear()
    // })
    // onMounted(() => console.log(emitter, '创建'))
    return {
        customEmit, customOn,
        toRefreshTable, refreshTable, toRefreshTree, refreshTree
    }
}
